package com.zbs.framework.security.filter;

import cn.hutool.core.util.URLUtil;
import com.zbs.framework.security.config.FrameworkConstants;
import com.zbs.framework.security.constant.SecurityConstants;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

import java.util.Collection;

/**
 * 动态权限决策管理器，用于判断用户是否有访问权限
 * Created by macro on 2020/2/7.
 */
@Configuration
public class DynamicAccessDecisionManager implements AccessDecisionManager {
 
    @Override
    public void decide(Authentication authentication, Object object,
                       Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        // 当接口未被配置资源时直接放行
        if (!FrameworkConstants.DO_OPEN_PERMISSIONS) {
            return;
        }
        //获取当前访问的路径
        String url = ((FilterInvocation) object).getRequestUrl();
        String path = URLUtil.getPath(url);

        if (FrameworkConstants.PERMISSIONS_MODEL.equals(SecurityConstants.ANNOTATIONS)) {
            Boolean flag = SecurityConstants.pathIsAnnotations.get(path);
            if (flag == null) {
                return;
            }
            if (!flag) {
                return;
            }
        }

        for (ConfigAttribute configAttribute : configAttributes) {
            //将访问所需资源或用户拥有资源进行比对
            String needAuthority = configAttribute.getAttribute();
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("抱歉，您没有访问权限");
    }
 
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }
 
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
 
}